package store

import (
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"
)

// 定义 REDIS客户端周围的结构包装器
type StorageService struct {
	redisClient *redis.Client
}

// 存储服务和redis上下文的最高级别声明
var (
	storeService = &StorageService{}
	ctx          = context.Background()
)

// 请注意，在现实世界中，缓存持续时间不应该为常量
// 到期时间，应将LRU策略配置设置为
// 从较少检索的值自动清除的值
// 每当缓存完成时，缓存并存储在RDBMS中
const CacheDuration = 6 * time.Hour

// 初始化存储服务,并返回一个指向存储服务的指针
func InitializeStore() *StorageService {
	redisClient := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "",
		DB:       0,
	})

	pong, err := redisClient.Ping(ctx).Result()
	if err != nil {
		panic(fmt.Sprintf("Error init Redis: %v", err))
	}
	fmt.Printf("\nRedis 连接启动成功: pong message = %v\n", pong)
	storeService.redisClient = redisClient
	return storeService
}

// 保存URL映射,并将其存储在Redis中
func SaveUrlMapping(shortUrl string, originalUrl string, userId string) {
	err := storeService.redisClient.Set(ctx, shortUrl, originalUrl, CacheDuration).Err()
	if err != nil {
		panic(fmt.Sprintf("存储url失败 | Error: %v - shortUrl: %s - originalUrl: %s\n", err, shortUrl, originalUrl))
	}

}

// 检索初始URL,并返回其值
func RetrieveInitialUrl(shortUrl string) (string, error) {
	result, err := storeService.redisClient.Get(ctx, shortUrl).Result()
	if err == redis.Nil {
		return "", fmt.Errorf("短链接不存在: %s", shortUrl)
	} else if err != nil {
		return "", fmt.Errorf("redis查询错误: %v", err)
	}
	return strings.TrimSpace(result), nil
}
